from collections import OrderedDict
from spider_xue.new_ip import check_duplicate_ip, clean_db_ip, clean_db_txt_ip, clean_dirty_db_ip, new_ip_obj
from db import *
import time
from spider_xue.settings import KEYS

keys = ['磷化工', '氟化工', '锂电池', '电力', '风电', '光伏', '电池', '锂', '新能源', '新能车', '汽车', '芯片']

def check(ts, ts2):
    if not ts2:
        all_records = record_db.find({"ts": {"$gte": ts}}).sort([("ts",  1)]) # , "$lte": ts
    else:
        all_records = record_db.find({"ts": {"$gte": ts, "$lte": ts2}}).sort([("ts",  1)]) # , "$lte": ts
    gg = {}
    for r in all_records:
        if r['symbol'] not in gg:
            gg[r['symbol']] = []
        gg[r['symbol']].append(r)
    ll = []
    for k,v in gg.items():
        sto = stock_db.find_one({"symbol": k})
        datad = data_day_db.find_one({"symbol": k})
        ct = 0
        for dd in datad['item'][-11:-1]:
            if dd[7] < 1:
                ct += 1
        if ct >= 7:
            continue
        all_msg = sto['gsjj'] + sto['hxtc'] + sto['jyfw']
    
        for kk in KEYS:
            if kk in all_msg:
                ll.append(sto['name'])
                print(k, sto['name'], time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(v[0]['ts'])), f'https://xueqiu.com/S/{k}')
                break
    print(len(ll))
    return ll


def check2(ts, ts2):
    if not ts2:
        all_records = record_db.find({"ts": {"$gte": ts}}).sort([("ts",  1)]) # , "$lte": ts
    else:
        all_records = record_db.find({"ts": {"$gte": ts, "$lte": ts2}, 'p15': {"$gte": 1}}).sort([("ts",  1)]) # , "$lte": ts

    gg = {}
    fail = []
    for r in all_records:
        if r['symbol'] not in gg:
            sto = stock_db.find_one({"symbol": r['symbol']})
            # print(sto['name'])
            r.pop("_id")
            if r['ts'] < ts + 34800 or r['ts'] > ts + 53700:
                fail.append(r['symbol'])
                continue
            else:
                if r['symbol'] in fail:
                    continue
                gg[r['symbol']] = r
                continue
        # gg[r['symbol']].append(r)
    
    ll = {}
    end = {}
    last = {}
    for k, v in gg.items():
        dayy = data_day_db.find_one({"symbol": k})
        
        lp = 0
        for ddday in range(0, len(dayy['item'])):
            if dayy['item'][ddday][0] == ts * 1000:
                lp = ddday
                break
        ct = 0
        for zzzz in dayy['item'][lp-10:lp]:
            if zzzz[7] <= 2:
                ct += 1
        if ct >= 7:
            continue
        if len(dayy['item']) <= lp+ 0:
            continue
        if dayy['item'][lp-1][7] < -8 or dayy['item'][lp-1][7] > 9:
            continue
        
        end[k] = dayy['item'][lp+0][5]
        last[k] = dayy['item'][lp-0][5]
        ll[k] = v
        print(v)

    
    zll = {}
    p = 0
    for k, v in ll.items():
        datad = data_five_db.find_one({"symbol": k})
        for dd in datad['item']:
            if v['ts'] * 1000 < dd[0]:
                gg[k] = dd[5]
                # record_db.update_one({"symbol": k, 'ts': v['ts']}, {"$set": {"price": dd[5]}})
                lddd = int((end[k]-dd[5]) / last[k] * 100)
                d = round((end[k]-dd[5]) / last[k] * 100, 2)

                p += d
                t = time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(v['ts']))
                print(k, v, t, dd[5], end[k], lddd)
                break
    # print(zll)
    # print(p)
    return zll
    
    # return ll


ts = 1635782400
x3 = check2(ts, ts + 86400)

# z = list(set(x1) & set(x2))
# z = list(set(x2) & set(x3))
# kk = list(x3.keys())
# print(time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(ts)))
# for i in sorted(kk):
#     print(i, x3[i])



def check3(ts, ts2):
    if not ts2:
        all_records = record_db.find({"ts": {"$gte": ts}}).sort([("ts",  1)]) # , "$lte": ts
    else:
        all_records = record_db.find({"ts": {"$gte": ts, "$lte": ts2}}).sort([("ts",  1)]) # , "$lte": ts

    gg = {}
    fail = []
    for r in all_records:
        if r['symbol'] not in gg:
            
            r.pop("_id")
            if 'p5' in r:
                if r['ts'] < ts + 34800 or r['ts'] > ts + 53700:
                    fail.append(r['symbol'])
                    continue
                else:
                    if r['symbol'] in fail:
                        continue
                    gg[r['symbol']] = r
                    continue

    for k, v in gg.items():
        dayy = data_day_db.find_one({"symbol": k})
        
        lp = 0
        for ddday in range(0, len(dayy['item'])):
            if dayy['item'][ddday][0] == ts * 1000:
                lp = ddday
                break
        ct = 0
        for zzzz in dayy['item'][lp-10:lp]:
            if zzzz[7] <= 2:
                ct += 1
        if ct >= 7:
            continue
        
        if dayy['item'][lp-1][7] < -8 or dayy['item'][lp-1][7] > 9:
            continue
        if round((v['price']-dayy['item'][lp-1][5]) / dayy['item'][lp-1][5] * 100, 2) > 8:
            continue
       
        # ll[k] = v
       
        if len(dayy['item']) > lp+1:
            enddd = dayy['item'][lp+1][5]
            l1 = round((enddd-v['price']) / v['price'] * 100, 2)
            v['l1'] = l1
            # v['e1'] = enddd
        
        if len(dayy['item']) > lp+2:
            enddd = dayy['item'][lp+2][5]
            l2 = round((enddd-v['price']) / v['price'] * 100, 2)
            v['l2'] = l2
            # v['e2'] = enddd
        
        if len(dayy['item']) > lp+3:
            enddd = dayy['item'][lp+3][5]
            l3 = round((enddd-v['price']) / v['price'] * 100, 2)
            v['l3'] = l3
            # v['e3'] = enddd
            
        if len(dayy['item']) <= lp+ 0:
            continue
        
        t = time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(v['ts']))
        # print(k, v, t, dd[5], end[k], lddd)
        v['date'] = t
        
        
        
        print(v)

# ts = 1635782400
# x3 = check3(ts, ts + 86400)


def ca3(ts, ts2):
    all = record_db.find({"ts": {"$gte": ts, "$lte": ts2}}).sort([('ts', 1)])
    time_dict = OrderedDict()
    
    for record in all:
        record.pop("_id")
        if record['date'] not in time_dict:
            time_dict[record['date']] = []
        if record['time'] >= '0940' and record['time'] < '1000':
            time_dict[record['date']].append(record)
        
        
    time_dict2 = OrderedDict()


    money1 = [100, 100]
    money2 = [100, 100 , 100]
    money3 = [100, 100 , 100, 100]
    count = 0
    for k, v in time_dict.items():
        index1 = count % 2
        index2 = count % 3
        index3 = count % 4
        print(k, "----------------------------")
        if v:
            l1, l2, l3 = 0, 0, 0
            l4, l5, l6 = 0, 0, 0
            l7, l8, l9 = 0, 0, 0
            lz = 0
            pz = 0
            if len(v) > 3:
                v = v[:3]
            for r in v:
                l1 += r['l1']/ 100
                l2 += r['l2']/ 100
                l3 += r['l3']/ 100
                if r['time'] <= '1130':
                    l4 += r['l1']/ 100
                    l5 += r['l2']/ 100
                    l6 += r['l3']/ 100
                    lz += 1
                else:
                    l7 += r['l1']/ 100
                    l8 += r['l2']/ 100
                    l9 += r['l3']/ 100
                    pz += 1
                print(r, l1, l2 ,l3)
            # last1 = round((1 + round(l1/len(v), 2)) * last1, 2)
            # last2 = round((1 +round(l2/len(v), 2)) * last2, 2)
            # last3 = round((1 +round(l3/len(v), 2)) * last3, 2)
            # if lz:
            #     last4 = round((1 +round(l3/lz, 2)) * last3, 2)
            #     last5 = round((1 +round(l3/lz, 2)) * last3, 2)
            #     last6 = round((1 +round(l3/lz, 2)) * last3, 2)
            # if pz:
            #     last7 = round((1 +round(l3/pz, 2)) * last3, 2)
            #     last8 = round((1 +round(l3/pz, 2)) * last3, 2)
            #     last9 = round((1 +round(l3/pz, 2)) * last3, 2)
            
            money1[index1] = round((1 +round(l1/len(v), 2)) * money1[index1], 2) 
            money2[index2] = round((1 +round(l2/len(v), 2)) * money2[index2], 2)
            money3[index3] = round((1 +round(l3/len(v), 2)) * money3[index3], 2)
            time_dict2[k] = [round(sum(money1) / 2, 2), round(sum(money2) / 3, 2), round(sum(money3) / 4, 2)]
            print(money1, money2, money3, time_dict2[k])
            
        else:
            time_dict2[k] = [round(sum(money1) / 2, 2), round(sum(money2) / 3, 2), round(sum(money3) / 4, 2)]

        count += 1
        
        
        
        # print(k, v)
    
    # for k, v in time_dict.items():
    #     print(k, "----------------------------")
    #     if len(v) > 3:
    #         v = v[-3:]
    #     for i in v:
    #         i.pop('_id')
    #         print(i)
    # for k, v in time_dict2.items():
    #     # print(v)
    #     # print(k + ',' + str(v[0]) + ',' + str(v[1]) + ',' + str(v[2]) + ',' + str(v[3]) + ',' + str(v[4]) + ',' + str(v[5]) + ',' + str(v[6]) + ',' + str(v[7]) + ',' + str(v[8]))
    #     print(k, v)
    
    return time_dict2
